import time
from django.utils.deprecation import MiddlewareMixin
import logging

req_logger = logging.getLogger('django.request')

class RequestLogMiddleware(MiddlewareMixin):
    '''记录所有http请求
    让每一个 HTTP 请求都自动被记录成日志。
    '''
    
    def process_request(self,request):
        # 记录请求开始时间
        request._start_time = time.time()
        
    def process_response(self, request, response):
        #计算请求处理时间
        try:
            duration = None
            if hasattr(request, '_start_time'): # 判断request对象是否有start_time属性
                duration = time.time() - request._start_time
                
            # 统一交给处理器，extra 带上 request/duration/status_code
            req_logger.info(
            f"{request.method} {request.path} 完成",
            extra={
                "request": request,
                "duration": duration,
                "status_code": getattr(response, "status_code", None),
            },
        )
            
        finally:
            return response
                
               
        
